/*
 * @Author: Liz.Zheng
 * @Date: 2021-09-29 20:29:45
 * @LastEditTime: 2022-02-14 13:47:42
 * @LastEditors: Please set LastEditors
 * @Description: 多语言
 * @Motto: Write the code. Change the world.
 */

import { createI18n } from "vue-i18n";
import { defaultLang, messages } from "./lang/lang.config.js";
import moment from "moment";

// 初始化多语言
const i18n = createI18n({
  globalInjection: true, //需要挂载到全局
  silentTranslationWarn: true,
  locale: defaultLang,
  fallbackLocale: defaultLang,
  messages,
});

// 已加载的语言列表
let loadedLanguages = [defaultLang];

/**
 * @description: 设置il8n多语言
 * @param {String} lang
 */
function setI18nLanguage(lang = defaultLang) {
  i18n.global.locale = lang;
  document.querySelector("html").setAttribute("lang", lang);
  return lang;
}

/**
 * @description: 加载多语言
 * @param {String} lang
 */
export function loadLanguageAsync(lang = defaultLang) {
  return new Promise((resolve, reject) => {
    // 缓存设置的语言
    // todo
    const { global } = i18n;
    if (global.locale !== lang) {
      console.log("loadLanguageAsync", i18n);
      if (!loadedLanguages.includes(lang)) {
        // 动态引入对应的翻译文件
        return import(`./lang/${lang}/index.js`).then((data) => {
          const locale = data.default;
          global.setLocaleMessage(lang, locale);
          loadedLanguages.push(lang);
          moment.locale(locale.momentName, locale.momentLocale)
          return setI18nLanguage(lang);
        });
      }
      return resolve(setI18nLanguage(lang));
    }
  });
}

export function L(key) {
  return i18n.global.t(`${key}`);
}

export default i18n;
